package com.jackchen.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jackchen.common.transform.TransformException;
import com.jackchen.common.transform.Transformer;
import com.jackchen.dao.CategoryDAO;
import com.jackchen.po.Category;
import com.jackchen.service.CategoryService;
import com.jackchen.vo.CategoryVO;

public class CategoryServiceImpl extends IBaseServiceImpl implements CategoryService {
	private static final Logger log = Logger.getLogger(CategoryServiceImpl.class);

	private CategoryDAO categoryDAO;

	public CategoryDAO getCategoryDAO() {
		return categoryDAO;
	}

	public void setCategoryDAO(CategoryDAO categoryDAO) {
		this.categoryDAO = categoryDAO;
	}

	@Override
	public List<CategoryVO> getCategorysByLanguage() {
		List<Category> categorys = categoryDAO.findAll("Category");
		List<Category> allcate = new ArrayList<Category>();
		Map<Integer, Category> keyMap = new HashMap<Integer, Category>();
		Map<Integer, List<Category>> keyListMap = new HashMap<Integer, List<Category>>();
		for(Category cate:categorys){
			if(cate.getLevel()==0){
				allcate.add(cate);				
				keyMap.put(cate.getId(), cate);
			}else{
				int pid = cate.getParentid();
				List<Category> lst = keyListMap.get(pid);
				if(lst==null){
					lst = new ArrayList<Category>();
					lst.add(cate);
					keyListMap.put(pid, lst);
				}else{
					lst.add(cate);
				}
			}
		}
		for(Map.Entry<Integer, List<Category>> e:keyListMap.entrySet()){
			int kid = e.getKey();
			List<Category> lst = e.getValue();
			keyMap.get(kid).setSubCategory(lst);
		}
		List<CategoryVO> dataList = null;
		try {
			dataList = Transformer.pojoToVos(keyMap.values(), CategoryVO.class);
		} catch (TransformException e) {
			// 数据转换失败
			dataList = Collections.emptyList();
		}
		return dataList; 
	}
	
	
}
